/*
    Searches for a text string in a text file.
    Version 1.0
    Date 20:30 21/07/2019
    By DreamVB
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TRUE 1
#define FALSE 0

int main(int argc, char**argv)
{
    FILE *fp = NULL;
    int mLineLen = 0;
    int mLineCount = 0 ;
    int x = 0;
    char ch = '\0';
    char s[1024];

    int IncludeNumbers = FALSE;
    int DoNotIncludeFound = FALSE;

    if(argc <= 1){
        printf("FINDSTR: Parameter format not correct.\n\n");
        printf("Searches for a text string in a file\n");
        printf("FINDSTR filename serach [options]\n");
        printf("\nOptions ::\n\n");
        printf(" /V Displays all lines not containing the specified string.\n");
        printf(" /N Include line numbers.\n");
        return 0;
    }

    fp = fopen(argv[1],"rb");

    if(fp == NULL){
        printf("Cannot read input file %s\n",argv[1]);
        return 0;
    }

    x = 3;

    //Process options
    while(x < argc){
        switch(argv[x][1]){
        case 'N':
        case 'n':
            IncludeNumbers = TRUE;
            break;
        case 'V':
        case 'v':
            DoNotIncludeFound = TRUE;
            break;
        }
        x++;
    }

    while((ch = fgetc(fp)) != EOF)
    {
        if(ch == '\n'){
            s[mLineLen - 1] = '\0';
            //Display all line not containing the string
            if(DoNotIncludeFound == TRUE){
                if(strstr(s,argv[2]) == 0){
                    if(IncludeNumbers == TRUE){
                        //Include line numbers
                        printf("[%d] ",(mLineCount + 1));
                    }
                    //Print lines
                    printf("%s\n",s);
                }
            }else{
                //Find all lines that contain the string.
                if(strstr(s,argv[2])){
                    if(IncludeNumbers == TRUE){
                        //Include line numbers
                        printf("[%d] ",(mLineCount + 1));
                    }
                    //Print lines
                    printf("%s\n",s);
                }
            }
            //Reset line length
            mLineLen = 0;
            //INC line counter
            mLineCount++;
        }else{
            //Build line
            s[mLineLen] = ch;
            //INC line length
            mLineLen++;
        }
    }
    fclose(fp);
    return 0;
}
